package filter

import (
	"log"
	global2 "longmen/server/config/global"
	"longmen/server/pkg/common/helper/blackWorlds/dfa/store"
	"sync"
	"time"
)

var instance *dirtyManager
var once sync.Once

func GetSensitiveWord() *dirtyManager {
	return instance
}

type dirtyManager struct {
	store  DirtyStore
	filter *DirtyManager
}

func InitWord(keyWords []string) *dirtyManager {
	//once.Do(func() {
	//	word, dirtyFilter := initSensitiveWord(keyWords)
	//	instance = &dirtyManager{
	//		filter: dirtyFilter,
	//		store:  word,
	//	}
	//})
	word, dirtyFilter := initSensitiveWord(keyWords)
	instance = &dirtyManager{
		filter: dirtyFilter,
		store:  word,
	}
	return instance
}

func initSensitiveWord(keyWords []string) (DirtyStore, *DirtyManager) {
	//filepath := "../../blackWords.txt"
	//fileData, err := ioutil.ReadFile(filepath)
	//if err != nil {
	//	log.Fatalln(err)
	//	return nil, nil
	//}
	//keyWords := strings.Split(string(fileData), ",")
	memStore, err := store.NewMemoryStore(store.MemoryConfig{
		DataSource: keyWords,
	})
	if err != nil {
		log.Fatalf("init DFA error: %v", err)
	}
	filterManager := NewDirtyManager(memStore, 5*time.Second)
	return memStore, filterManager
}

func (d dirtyManager) AddWordsSlice(plainText []string) error {
	return d.filter.Store().Write(plainText...)
}

func (d dirtyManager) AddWords(plainText ...string) error {
	return d.filter.Store().Write(plainText...)
}

func (d dirtyManager) DeleteWords(plainText ...string) error {
	return d.filter.Store().Remove(plainText...)
}

func (d dirtyManager) Replace(plainText string) (string, error, bool) {
	replace, err := d.filter.Filter().Replace(plainText, '*')
	global2.Log.Debugf("replace:%s,text:%s", replace, plainText)
	if err == nil && replace == "" {
		return plainText, err, false
	}
	return replace, err, true
}

// 返回是不是有包含敏感词true就是有
func (d dirtyManager) Filter(text string) (bool, error) {
	replace, err := d.filter.Filter().Filter(text)
	return len(replace) > 0, err
}
